package com.chinatechstar.component.commons.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.chinatechstar.component.commons.exception.ServiceException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

/**
 * Excel工具类
 * 
 * @版权所有 上海至界信息科技有限公司 
 */
public class ExcelUtils {
//
//	@Value("${studio.cer-personinfo-file-in-disk}")
//	private String cerPersonFileInDisk;
	private ExcelUtils() {

	}

	/**
	 * 导出Excel
	 *
	 * @param headList  Excel表头列表
	 * @param dataList  Excel内容列表
	 * @param sheetName Excel工作表名称
	 * @param response  响应对象
	 * @throws IOException
	 */
	public static void exportExcel(List<String> headList, List<LinkedHashMap<String, Object>> dataList, String sheetName, HttpServletResponse response)
			throws IOException {
		ServletOutputStream servletOutputStream = null;
		try {
			servletOutputStream = response.getOutputStream();
			response.setContentType("multipart/form-data");
			response.setCharacterEncoding("utf-8");
			String fileName = new String((sheetName + new SimpleDateFormat("yyyy-MM-dd").format(new Date())).getBytes(), StandardCharsets.UTF_8);
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
			ExcelWriter writer = new ExcelWriter(servletOutputStream, ExcelTypeEnum.XLSX, true);
			Sheet sheet = new Sheet(1, 0);
			sheet.setSheetName(sheetName);

			Table table = new Table(1);
			List<List<String>> head = new ArrayList<>();
			if (!CollectionUtils.isEmpty(headList)) {
				headList.forEach(headName -> head.add(Arrays.asList(headName)));
			}
			table.setHead(head);

			List<List<String>> data = new ArrayList<>();
			if (!CollectionUtils.isEmpty(dataList)) {
				dataList.forEach(map -> {
					List<String> list = new ArrayList<>();
					for (Entry<String, Object> entry : map.entrySet()) {
						Object value = entry.getValue();
						list.add(value == null ? null : value.toString());
					}
					data.add(list);
				});
			}

			writer.write0(data, sheet, table);
			writer.finish();
			servletOutputStream.flush();
		} catch (IOException e) {
			throw new ServiceException(e.toString());
		} finally {
			if (servletOutputStream != null) {
				servletOutputStream.close();
			}
		}
	}

	public static String downloadExcel(List<String> headList, List<LinkedHashMap<String, Object>> dataList, String sheetName, HttpServletResponse response,String filePath)
			throws IOException {
		String fileName = new String((sheetName + new SimpleDateFormat("yyyy-MM-dd").format(new Date())+SnowflakeIdUtil.getSnowflakeId()).getBytes(), StandardCharsets.UTF_8);
		File file = new File(filePath+"/"+fileName+".xlsx");
		FileOutputStream fileOutputStream = new FileOutputStream(file);
		try {
            /*servletOutputStream = response.getOutputStream();
			response.setContentType("multipart/form-data");
			response.setCharacterEncoding("utf-8");*/

//			response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
			ExcelWriter writer = new ExcelWriter(fileOutputStream, ExcelTypeEnum.XLSX, true);
			Sheet sheet = new Sheet(1, 0);
			sheet.setSheetName(sheetName);

			Table table = new Table(1);
			List<List<String>> head = new ArrayList<>();
			if (!CollectionUtils.isEmpty(headList)) {
				headList.forEach(headName -> head.add(Arrays.asList(headName)));
			}
			table.setHead(head);

			List<List<String>> data = new ArrayList<>();
			if (!CollectionUtils.isEmpty(dataList)) {
				dataList.forEach(map -> {
					List<String> list = new ArrayList<>();
					for (Entry<String, Object> entry : map.entrySet()) {
						Object value = entry.getValue();
						list.add(value == null ? null : value.toString());
					}
					data.add(list);
				});
			}

			writer.write0(data, sheet, table);
			writer.finish();
			fileOutputStream.flush();
		} catch (IOException e) {
			throw new ServiceException(e.toString());
		} finally {
			if (fileOutputStream != null) {
				fileOutputStream.close();
			}
		}
		return fileName+".xlsx";
	}

	public static File downloadExcelFile(List<String> headList, List<LinkedHashMap<String, Object>> dataList, String sheetName, HttpServletResponse response,String filePath)
			throws IOException {
		String fileName = new String((sheetName + new SimpleDateFormat("yyyy-MM-dd").format(new Date())+SnowflakeIdUtil.getSnowflakeId()).getBytes(), StandardCharsets.UTF_8);
		Path path = Paths.get(filePath);
		if (!Files.exists(path)) {
			Files.createDirectories(path);
		}
		File file = new File(filePath+"/"+fileName+".xlsx");

		try (FileOutputStream fileOutputStream = new FileOutputStream(file)){
			ExcelWriter writer = new ExcelWriter(fileOutputStream, ExcelTypeEnum.XLSX, true);
			Sheet sheet = new Sheet(1, 0);
			sheet.setSheetName(sheetName);

			Table table = new Table(1);
			List<List<String>> head = new ArrayList<>();
			if (!CollectionUtils.isEmpty(headList)) {
				headList.forEach(headName -> head.add(Arrays.asList(headName)));
			}
			table.setHead(head);

			List<List<String>> data = new ArrayList<>();
			if (!CollectionUtils.isEmpty(dataList)) {
				dataList.forEach(map -> {
					List<String> list = new ArrayList<>();
					for (Entry<String, Object> entry : map.entrySet()) {
						Object value = entry.getValue();
						list.add(value == null ? null : value.toString());
					}
					data.add(list);
				});
			}

			writer.write0(data, sheet, table);
			writer.finish();
			fileOutputStream.flush();
		} catch (IOException e) {
			throw new ServiceException(e.toString());
		} /*finally {
			if (fileOutputStream != null) {
				fileOutputStream.close();
			}
		}*/
		return file;
	}
//
//	private static String generateCerDataInitFileSavePath(MultipartFile file, String userId) {
//		// 生成新的文件名称
//		String fileName =
//				DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS") + "_" + userId + "_" + file
//						.getOriginalFilename()
//						.substring(0,
//								file
//										.getOriginalFilename()
//										.lastIndexOf('.')) + file
//						.getOriginalFilename()
//						.substring(file
//								.getOriginalFilename()
//								.lastIndexOf('.'));
//
//		// 生成文件的存放路径
//		// 日期目录
//		String dirName = cerPersonFileInDisk + DateFormatUtils.format(new Date(), "yyyyMMdd");
//		System.out.println(cerPersonFileInDisk);
//		System.out.println(dirName);
//		File dir = new File(dirName);
//		if (!dir.exists()) {
//			dir.mkdirs();
//		}
//		return dirName + "/" + fileName;
//	}
//
//	public static File commonImportConfig(MultipartFile file, String userId ){
//		File tmpfile = new File(generateCerDataInitFileSavePath(file,userId));
//		try {
//			FileUtils.copyInputStreamToFile(file.getInputStream(), tmpfile);
//		} catch (IOException e) {
//			throw new RuntimeException(e);
//		}
//		return tmpfile;
//	}
}
